<template>
  <el-card shadow="never" class="border-0">
    <list-header @create="handleCreate" @refresh="getData" />

    <el-table :data="tableData" stripe style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="角色名称" />
      <el-table-column prop="desc" label="角色描述" />
      <el-table-column label="状态">
        <template #default="{ row }">
          <el-switch
            :modelValue="row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange($event, row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            text
            @click="openSetRoleDialog(scope.row)"
          >
            权限配置
          </el-button>

          <el-button
            type="primary"
            size="small"
            text
            @click="handleEdit(scope.row)"
          >
            修改
          </el-button>
          <el-popconfirm
            title="是否要删除该公共？ "
            confirmButtonText="确认"
            cancelButtonText="取消"
            @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" text> 删除 </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="flex items-center justify-center mt-5">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="limit"
        @current-change="getData"
      />
    </div>

    <form-drawer
      ref="formDrawerRef"
      :title="drawerTitle"
      @submit="handleSumbit"
      @cancel="handleCancel"
    >
      <el-form
        :model="form"
        ref="formRef"
        :rules="rules"
        label-width="80px"
        :inline="false"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入角色描述" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="0"
            :inactive-value="1"
          />
        </el-form-item>
      </el-form>
    </form-drawer>

    <!-- 配置角色 -->
    <form-drawer
      ref="setRoleRef"
      title="权限配置"
      @submit="handleRoleSumbit"
      @cancel="handleRoleCancel"
    >
      <el-tree-v2
        ref="elTreeRef"
        node-key="id"
        :default-expanded-keys="defaultExpandedKeys"
        :data="ruleList"
        :props="{ label: 'name', children: 'child' }"
        :check-strictly="checkStrictly"
        show-checkbox
        :height="treeHeight"
        @check="handleTreeCheck"
      >
        <template #default="{ node, data }">
          <div class="flex items-center">
            <el-tag :type="data.menu ? '' : 'info'" size="small">
              {{ data.menu ? '菜单' : '权限' }}
            </el-tag>
            <span class="ml-2 text-sm"> {{ data.name }} </span>
          </div>
        </template>
      </el-tree-v2>
    </form-drawer>
  </el-card>
</template>

<script setup>
  import { ref } from 'vue'
  import {
    getRoleListApi,
    createRoleApi,
    updateRoleApi,
    deleteRoleApi,
    updateRoleStatusApi,
    setRoleRulesApi,
  } from '@/api/role.js'
  import { getRuleListApi } from '@/api/rule.js'
  import FormDrawer from '@/components/FormDrawer.vue'
  import { useInitTable, useInitForm } from '@/hooks/useCommon.js'
  import ListHeader from '@/components/ListHeader.vue'
  import { toast } from '@/utils'

  const {
    tableData,
    loading,
    currentPage,
    total,
    limit,
    getData,
    handleDelete,
    handleStatusChange,
  } = useInitTable({
    getlist: getRoleListApi,
    delete: deleteRoleApi,
    updateStatus: updateRoleStatusApi,
  })

  const {
    formRef,
    formDrawerRef,
    form,
    rules,
    drawerTitle,
    editId,
    handleCreate,
    handleEdit,
    handleSumbit,
    handleCancel,
  } = useInitForm({
    form: {
      name: '',
      desc: '',
      status: 1,
    },
    rules: {
      name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
    },
    getData,
    create: createRoleApi,
    update: updateRoleApi,
  })

  // 配置角色
  const setRoleRef = ref(null)
  const ruleList = ref([])
  const treeHeight = ref(0)
  const defaultExpandedKeys = ref([])
  const roleId = ref(0)
  const elTreeRef = ref(null)
  const checkStrictly = ref(false)

  // 当前用户拥有的权限id
  const roleIds = ref([])
  function openSetRoleDialog(row) {
    roleId.value = row.id
    treeHeight.value = window.innerHeight - 180
    checkStrictly.value = true

    getRuleListApi(1).then((res) => {
      ruleList.value = res.list
      defaultExpandedKeys.value = res.list.map((o) => o.id)
      setRoleRef.value.open()

      // 当前角色拥有的权限id，必须在弹窗打开后执行
      roleIds.value = row.rules.map((o) => o.id)
      setTimeout(() => {
        elTreeRef.value?.setCheckedKeys(roleIds.value)
        checkStrictly.value = false
      }, 150)
    })
  }

  function handleTreeCheck(...e) {
    const { checkedKeys, halfCheckedKeys } = e[1]
    roleIds.value = [...checkedKeys, ...halfCheckedKeys]
  }

  function handleRoleCancel() {
    setRoleRef.value.close()
  }

  function handleRoleSumbit() {
    setRoleRef.value.showLoading()
    setRoleRulesApi(roleId.value, roleIds.value)
      .then((res) => {
        toast('配置成功')
        getData()
        setRoleRef.value.close()
      })
      .finally(() => setRoleRef.value.hideLoading())
  }
</script>

<style scoped></style>
